package com.gwt.mavenized.sample.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Application implements EntryPoint {

	final Label label = new Label("Enter Your Name:");
	final TextBox textBox = new TextBox();
	final Button button = new Button("Greet Server");
	final DialogBox dialogBox = new DialogBox(true);

	/* Create a remote service proxy to talk to the server-side Greeting service. */
	private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		dialogBox.setAnimationEnabled(true);
		VerticalPanel vPanel = new VerticalPanel();
		vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		vPanel.add(label);
		vPanel.add(textBox);
		vPanel.add(button);
		addButtonClickHandler(button);
		RootPanel.get().add(vPanel);
	}

	/**
	 * @param button
	 */
	private void addButtonClickHandler(final Button button) {
		button.addClickHandler(new ClickHandler() {
			public void onClick(final ClickEvent aClickEvent) {
				ServiceDefTarget target = (ServiceDefTarget) greetingService;
				target.setServiceEntryPoint(GWT.getModuleBaseURL() + "greet");
				greetingService.greetServer(textBox.getText(), new AsyncCallback<String>() {
					public void onSuccess(final String serverResponse) {
						showDialogue(serverResponse);
					}

					public void onFailure(final Throwable aServerException) {
						showDialogue(aServerException.getMessage());
					}
				});
			}
		});
	}

	/**
	 * @param serverResponse
	 */
	private void showDialogue(final String serverResponse) {
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.setSpacing(5);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		dialogVPanel.add(new HTML(serverResponse));
		dialogBox.setWidget(dialogVPanel);
		dialogBox.center();
		dialogBox.show();
	}
}
